package com.salary.utils.reader;

import com.salary.model.CoefficientEntry;
import org.apache.poi.ss.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CoefficientDataReader extends DataReader<List<CoefficientEntry>> {
    private static final Logger logger = LoggerFactory.getLogger(CoefficientDataReader.class);

    @Override
    /**
     * 从Excel文件读取系数表数据
     *
     * @param filePath Excel文件路径
     * @return 系数表条目列表
     */
    public List<CoefficientEntry> readData(String filePath) {

        List<CoefficientEntry> entries = new ArrayList<>();

        try (FileInputStream fis = new FileInputStream(filePath);
             Workbook workbook = WorkbookFactory.create(fis)) {

            Sheet sheet = workbook.getSheetAt(0); // 默认使用第一个工作表
            if (sheet == null) {
                logger.error("系数表中没有找到工作表");
                return entries;
            }

            // 查找姓名和系数列
            Map<String, Integer> columnMap = new HashMap<>();
            Row headerRow = sheet.getRow(0);
            if (headerRow == null) {
                logger.error("系数表没有标题行");
                return entries;
            }

            for (int i = 0; i < headerRow.getLastCellNum(); i++) {
                Cell cell = headerRow.getCell(i);
                if (cell != null) {
                    String columnName = cell.getStringCellValue().trim();
                    columnMap.put(columnName, i);
                }
            }

            // 确认所需列存在
            if (!columnMap.containsKey("姓名") || !columnMap.containsKey("系数")) {
                logger.error("系数表中缺少必要的列：姓名、系数");
                return entries;
            }

            int nameColIndex = columnMap.get("姓名");
            int coefficientColIndex = columnMap.get("系数");

            // 读取数据行
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                String name = getCellValueAsString(row.getCell(nameColIndex));

                // 跳过空行
                if (name.isEmpty()) continue;

                double coefficient = 1.0; // 默认系数为1.0
                Cell coefficientCell = row.getCell(coefficientColIndex);
                if (coefficientCell != null) {
                    coefficient = getCellValueAsDouble(coefficientCell);
                }

                entries.add(new CoefficientEntry(name, coefficient));
                logger.info("读取系数表数据：" + name + ", 系数: " + coefficient);
            }

            logger.info("成功读取系数表，共 " + entries.size() + " 条记录");

        } catch (IOException e) {
            logger.error("读取系数表失败: " + e.getMessage(), e);
        }

        return entries;
    }

}
